<template>
  <div>
    <!-- 新增文章 -->
    <div  class="dialog-class">
      <div>
        <el-button type="primary" style="margin-left: 16px" @click="open">
        添加文章
        </el-button>

        <el-drawer
          v-model="drawer"
          :title="articlename"
          :before-close="handleClose"
        >
          <articlefrom :Form="ruleFormzeng" :fenleiList="categoryList"
          @shuaxin="getfenlei"/>
        </el-drawer>
      </div>

      <div class="wenjian">
        <div style="margin-right: 16px">
          <!-- 文件的导入 -->
          <el-upload

            ref="uploadRef"

            class="upload-demo"

            action="http://localhost:8080/article/importData"

            :auto-upload="true"

            :on-success="uploadsuccess">

            <template #trigger>

            <el-button type="primary">导入文章</el-button>

            </template>

          </el-upload>
        </div>

        <!-- 文件的导出 -->
        <div>
          <el-button type="primary" @click="daochu">导出文章</el-button>
        </div>
        
      </div>

    </div>
    <!-- 文章信息 -->
    <tabledata :tableData="tableData" 
      @xiangqing="xiangqing" @delArticle="handleClick" @bianji="bianji"
    />
    <!-- 分页查文章信息 -->
    <div class="pagination">
      <el-pagination
        :current-page="canshu.pageNum"
        :page-size="canshu.pageSize"
        :page-sizes="[1, 2, 3, 4]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="canshu.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 文章详情 -->
    <el-dialog
      v-model="dialogVisible"
      title="文章详情"
      width="900px"
    >
      <span>
        <el-table :data="tableDataxiang" style="width: 100%">
          <el-table-column prop="title" label="文章标题" width="180" />
          <el-table-column prop="category" label="文章分类" width="180" >
            <template v-slot="scope">
                <el-tag>{{ scope.row.category.categoryName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="content" label="文章内容" width="180" />
          <el-table-column prop="createTime" label="创建日期" />
          <el-table-column prop="state" label="状态" />
          <el-table-column prop="coverImg" label="文章封面">
            <template v-slot="scope">
              <img :src="scope.row.coverImg" alt="封面" style="width: 100px; height: auto;" />
            </template>
          </el-table-column>
        </el-table>
      </span>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive,onMounted} from 'vue'
// 引入提示框
import { ElMessage,ElMessageBox} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
//引入pinia
import {useUserStore} from '@/stores/token.js'; 
// 引入请求
import { fenlei,savearticle,deletearticle,updatearticle,export01} from '@/api/article.js'
import {selectleixingId} from '@/api/category.js'

//引入子组件
import tabledata from '@/components/tabledata.vue'
import articlefrom from '@/components/articlefrom.vue'

//获取容器对象
const us=useUserStore(); 
//获取容器对象中的数据
console.log(us.denglu); 
//获取登录人的id
const id=us.denglu.id;

//导入文件成功后的回调
const uploadsuccess=(result)=>{
    console.log(result);
 if(result.code==60001){

  ElMessage.success(result.msg);

 }else{

  ElMessage.error(result.msg);

 }

}

//导出文章
const daochu=()=>{
   daochudiao();
}
const daochudiao=async()=>{
  // 根据这个人的id，查询这个人所写的所有文章
  const result=await export01(id);
        //前端拿到数据后，开始组织下载文件
        console.log('Blob size:', result.size); // 打印文件大小
        const url = window.URL.createObjectURL(result);
        const a = document.createElement('a');
        a.href = url;
        a.download = 'people.xls'; // 设置下载的文件名
        document.body.appendChild(a);
        a.click();
        a.remove();
        window.URL.revokeObjectURL(url);
}

// 定义表格数据
const tableData = ref([])
//定义分页参数
const canshu=ref({
  pageNum:1,
  pageSize:2,
  total:0,
  object:id
})
console.log(canshu.value)
//获取登录人的id
const getfenlei = async(obj) =>{
  drawer.value=false;
  const res=await fenlei(canshu.value);
  console.log(res);
  if(res.code==20041){
        ElMessage({
            message: res.msg,
            type: 'success',
            plain: true,
        })
       tableData.value=res.data.list;
       console.log(tableData.value);
       canshu.value.total=res.data.total;
    }else{
       ElMessage({
            message: res.msg,
            type: 'error',
            plain: true,
        })
    }
}
//当你修改每页条数时触发该事件
const handleSizeChange = (val) => {
  canshu.value.pageSize=val;  //把选中的每页显示条数赋值给canshu.pageSize
  getfenlei(); //重新调用getfenlei方法
}
//当你修改页码时会触发该事件
const handleCurrentChange = (val) => {
  canshu.value.pageNum=val; //把点击的页码赋值给canshu.pageNum
  getfenlei();  //重新调用getfenlei方法
}

//删除文章
const shanchu= async(id)=>{
  const res= await deletearticle(id);
    console.log(res);
    if(res.code==20021){
          ElMessage({
              message: res.msg,
              type: 'success',
              plain: true,
          })
          getfenlei();
      }else{
        ElMessage({
              message: res.msg,
              type: 'error',
              plain: true,
          })
      }
}
const handleClick = (id) => {
  ElMessageBox.confirm(
    '确认删除吗？',
    {
      confirmButtonText: 'OK',
      cancelButtonText: 'Cancel',
      type: 'warning',
    }
  )
    .then(() => {
      shanchu(id);
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      })
    })
}

//文章操作
const articlename=ref('')

//控制抽屉是否显示 false不显示
const drawer = ref(false)

// 添加文章表单数据
const ruleFormzeng=ref({
  title:'',   //文章标题
  content:'',  //文章内容
  state:'',   //文章状态
  categoryId:'',  //文章分类
  coverImg:'',  //文章封面
  createUser:'',  //文章作者
})

//存放文章分类的集合
const categoryList = ref([]);
//查询所有文章分类
const selectsuoyou=async()=>{
  const res=await selectleixingId(id);
  console.log(res);
  if(res.code==20041){
        ElMessage({
            message: res.msg,
            type: 'success',
            plain: true,
        })
        // 把查询到的数据赋值给categoryList
      categoryList.value=res.data;
    }else{
       ElMessage({
            message:res.msg,
       })
    }
}
//打开添加文章抽屉
const open=()=>{
  articlename.value='添加文章';
  drawer.value = true;
  //清空文章表单
  ruleFormzeng.value={}
  selectsuoyou();
  if (quillEditorRef.value) {
    quillEditorRef.value.setContents([]); // 清空富文本编辑器内容
  }
}

//点击编辑按钮
const bianji= async(row)=>{
  ruleFormzeng.value=row;
  console.log(ruleFormzeng.value)
  articlename.value='编辑文章';
  drawer.value = true;
  selectsuoyou();
}

//文章详情
const dialogVisible = ref(false)
const tableDataxiang = ref([])
const xiangqing= async(id)=>{
  dialogVisible.value = true
  const res=await savearticle(id);
  console.log(res);
  if(res.code==20041){
        ElMessage({
            message: res.msg,
            type: 'success',
            plain: true,
        })
      tableDataxiang.value=[res.data];
    }else{
       ElMessage({
            message: res.msg,
            type: 'error',
            plain: true,
        })
    }
}

//定义生命周期
//当页面加载完成时，执行onMounted
onMounted(()=>{
   getfenlei();
})
</script>

<style lang='scss' scoped>
.dialog-class{
  margin-bottom: 10px;
  display: flex;
  justify-content:space-between
}
.pagination{
  margin-top: 10px;
}
.wenjian{
    display: flex;
  }
</style>